package io.kiki.sba.registry.server.shared.remoting;

import io.kiki.sba.registry.api.Channel;
import io.kiki.sba.registry.common.model.Node;
import io.kiki.sba.registry.common.model.Response;
import io.kiki.sba.registry.common.model.metaserver.SlotsChangeEvent;
import io.kiki.sba.registry.server.shared.meta.MetaServerService;
import io.kiki.sba.registry.util.StringFormatter;
import lombok.NonNull;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;


public class SlotsChangeEventHandler extends AbstractClientHandler<SlotsChangeEvent> {

    @Autowired
    MetaServerService metaServerService;

    @Autowired
    ThreadPoolExecutor metaNodeExecutor;

    @Override
    protected Node.NodeType getConnectNodeType() {
        return Node.NodeType.central_control;
    }

    @Override
    public void checkParam(@NonNull SlotsChangeEvent request) {

        super.checkParam(request);
        //ParaCheckUtil.checkIsPositive(request.getSlotsEpoch(), "SlotsChangeEvent.slotsEpoch");
        if (request.getSlotsEpoch() <= 0) {
            throw new IllegalArgumentException(StringFormatter.format("{} is require positive, {}", "SlotsChangeEvent.slotsEpoch", request.getSlotsEpoch()));
        }

    }

    @Override
    public Object doHandle(Channel channel, SlotsChangeEvent request) {
        boolean result = metaServerService.handleSlotsChange(request);
        if (result) {
            return Response.buildSuccessResponse("successfully triggered slot-table retrieval");
        } else {
            return Response.buildFailedResponse("won't update slot-table, check [AbstractMetaServerService] log");
        }
    }

    @Override
    public Object buildFailedResponse(String msg) {
        return Response.buildFailedResponse(msg);
    }

    @Override
    public Class interest() {
        return SlotsChangeEvent.class;
    }

    @Override
    public Executor getExecutor() {
        return metaNodeExecutor;
    }
}
